import { memo, useEffect, useState } from 'react'
import { Input } from 'antd'
import type { SearchProps } from 'antd/lib/input'
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom'

const { Search } = Input

const ListSearch = memo(() => {
  const [value, setValue] = useState('')
  const nav = useNavigate()
  const { pathname } = useLocation()

  const onChange: SearchProps['onChange'] = e => {
    setValue(e.target.value)
  }

  const onSearch: SearchProps['onSearch'] = value => {
    if (value) {
      nav({
        pathname,
        search: `?keyword=${value}`,
      })
    } else {
      nav(pathname)
    }
  }

  const [searchParams] = useSearchParams()
  useEffect(() => {
    const newVal = searchParams.get('keyword') || ''
    setValue(newVal)
  }, [searchParams])

  return (
    <Search
      placeholder="请输入关键字"
      allowClear
      value={value}
      onChange={onChange}
      onSearch={onSearch}
      style={{ width: 250 }}
    />
  )
})

export default ListSearch
